# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

from pylons import request, url
from webhelpers.paginate import Page

from chowa.lib.base import Session
from chowa.model.site import App
from chowa.model.navigation import Tab as TabModel, TabSet

class NavigationItem(object):
    def __init__(self,
                 params=dict(),
                 prefix=None, url=None,
                 ignore_params=[], ignore_all=False,
                 caption='', description='',
                 generator=None):
        if generator:
            self = generator()
        else:
            self.params = params
            self.url = url
            self.prefix = prefix
            self.ignore_params = ignore_params
            self.ignore_all = ignore_all
            self.caption = caption
            self.description = description
    
    def get_url(self):
        if self.url:
            return self.url
        else:
            routing_vars = request.environ['pylons.routes_dict']
            extended = self.params.copy()
            for param in extended:
                if type(extended[param]) == list and extended[param]:
                    extended[param] = extended[param][0]
                if 'default__' in param:
                    new_param = param.replace('default__', '')
                    extended[new_param] = extended[param]
                    del extended[param]
            if not self.ignore_all:
                for param in routing_vars:
                    if param not in extended and param not in self.ignore_params:
                        extended[param] = routing_vars[param]
            return url(**extended)
    
    def verify(self):
        if self.url:
            current_url = request.environ.get('SCRIPT_NAME') + request.environ.get('PATH_INFO')
            if self.prefix:
                return current_url.startswith(self.prefix)
            else:
                return current_url == self.url
        else:
            routing_vars = request.environ['pylons.routes_dict']
            for param in self.params:
                if not param.startswith('default__'):
                    if param in routing_vars:
                        if type(self.params[param]) == list:
                            if not routing_vars[param] in self.params[param]:
                                return False
                        else:
                            if (routing_vars[param] != self.params[param]):
                                return False
                    else:
                        return False
        return True
    
    
def install_menus():
    pass

class Menu(object):
    def __init__(self, name, caption='', items=[], protector=None):
        self.name = name
        self.caption = caption
        self.items = items
        self.protector = protector

class MenuItem(NavigationItem): pass
class Tab(NavigationItem): pass


def url_generator(**kwargs):
    params = request.params.copy()
    for key in kwargs:
        if key in params:
            del params[key]
    new_kwargs = dict(kwargs.items() + params.items())
    return url.current(**new_kwargs)


def url_outside(appname, **kwargs):
    _url = url(**kwargs)
    script_name = request.environ.get('SCRIPT_NAME')
    if _url.startswith(script_name):
        _url = _url[len(script_name):]
        app = Session.query(App).filter_by(name=appname).one()
        prefix = app.url_prefix
        # FIXME: join url with prefix
        if prefix[-1] == '/': prefix = prefix[:-1]
        _url = prefix + _url
    return _url


def get_page(query, items_per_page=10):
    current_page = 1
    if request.params.has_key('page'):
        current_page = int(request.params['page'])
    page = Page(query,
                page=current_page,
                items_per_page=items_per_page,
                url=url_generator)
    return page


def get_global_tabs(level):
    tabsets = Session.query(TabSet).filter_by(level=level).all()
    return [[Tab(url=tab.url, prefix=tab.prefix, caption=tab.caption)
             for tab in tabset.tabs]
            for tabset in tabsets]
